﻿using ModuleBase.googoltech.GTS;
using ModuleBase;
using Prism.Ioc;
using Newtonsoft.Json;
using System.Diagnostics;
using Newtonsoft.Json.Linq;

namespace AxisHome
{
    public class AxisHome : ModuleBase.ModuleBase
    {
        private IAxisCardService _axisCardService;
        private ModuleStateService _moduleStateService;
        bool outputs = false;
        bool isExecuted = false;
        private IContainerProvider _containerProvider;
        bool HomeFinishFlag = false;
        int finishCount = 0;
        int workCount = 0;

        private string _parameter1;
        public string Parameter1
        {
            get => _parameter1;
            set
            {
                if (_parameter1 != value)
                {
                    _parameter1 = value;
                    OnPropertyChanged(nameof(Parameter1));
                }
            }
        }
        private string _parameter2 = "Top_A8";
        public string Parameter2
        {
            get => _parameter2;
            set
            {
                if (_parameter2 != value)
                {
                    _parameter2 = value;
                    OnPropertyChanged(nameof(Parameter2));
                }
            }
        }
        public override Dictionary<string, object> GetProperties()
        {
            return new Dictionary<string, object>
            {
                { "轴号", Parameter1 },
                { "轴参数名", Parameter2 },
            };
        }

        public AxisHome(IContainerProvider containerProvider, ModuleStateService moduleStateService)
        {
            _containerProvider = containerProvider;
            _moduleStateService = moduleStateService;
            Name = "直线电机回原点";

            DisplayNameToPropertyNameMap = new Dictionary<string, string>
            {
                { "轴号", nameof(Parameter1) },
                { "轴参数名", nameof(Parameter2) },
            };
        }

        public override bool Execute()
        {
            Status = ModuleStatus.Executing; // 设置状态为执行中

            if (isExecuted)
            {
                outputs = true;
                return outputs;
            }

            _axisCardService = _containerProvider.Resolve<IAxisCardService>(Parameter2);
            var param = Parameter1.ToString().Split(',', '，');
            if (param != null && param.Length > 0)
            {
                try
                {
                    workCount = param.Length;
                    param.ToList().ForEach(p =>
                    {
                        AxisParm _axis = GetAxisByNumber(int.Parse(p));
                        GTSCard.AxisPosSet(_axis, GTSCard.GetEnc(_axis));
                        CancellationTokenSource source1 = new CancellationTokenSource();
                        CancellationToken token1 = source1.Token;
                        HomeFinishFlag = false;
                        MyFunc.AddMessage($"轴[{_axis.AxisId}]开始回原点");
                        Task.Run(() => Home(token1, _axis), token1);
                        //outputs = true;
                        //isExecuted = true;
                    });

                    while (finishCount < workCount)
                    {
                        outputs = true;
                        isExecuted = true;
                        Thread.Sleep(1000);
                    }
                }
                catch
                {
                    outputs = false;
                }
            }
            else { outputs = false; }

            return outputs;
        }

        public override async Task<bool> ExecuteAsync()
        {
            outputs = false;
            var result = await Task.Run(() => Execute());
            return result;
        }

        public override void Initialize()
        {
            isExecuted = false;
        }
        private AxisParm GetAxisByNumber(int axisNumber)
        {
            switch (axisNumber)
            {
                case 1: return _axisCardService.A1;
                case 2: return _axisCardService.A2;
                case 3: return _axisCardService.A3;
                case 4: return _axisCardService.A4;
                case 5: return _axisCardService.A5;
                case 6: return _axisCardService.A6;
                case 7: return _axisCardService.A7;
                case 8: return _axisCardService.A8;
                default: return _axisCardService.A1;
            }
        }

        private void Home(CancellationToken token, AxisParm axis)
        {
            bool Homed = false;
            int stepnum = 0;
            int actionCount = 0;
            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }
                switch (stepnum)
                {
                    case 0:
                        if (!Homed)
                        {
                            stepnum = 3;
                        }
                        else
                        {
                            MyFunc.AddMessage($"轴[{axis.AxisId}]已回原点");
                            return;
                        }
                        break;
                    case 3:
                        if (!_moduleStateService.IsStopped)
                        {
                            GTSCard.AxisHomeMove(axis);
                            stepnum = 4;
                        }
                        break;
                    case 4:
                        if (!_moduleStateService.IsStopped)
                        {
                            if (GTSCard.AxisHomeCheckDone(axis))
                            {
                                actionCount++;
                                if (actionCount > 1)
                                {
                                    System.Threading.Thread.Sleep(2000);
                                    GTSCard.AxisZeroSet(axis);
                                    GTSCard.AxisPosSet(axis, 0);
                                    GTSCard.AxisEncSet(axis, 0);
                                    GTSCard.AxisSynchAxisPos(axis);
                                    GTSCard.SetSoftLimit(axis);
                                    GTSCard.ClearAlm1(axis);
                                    Homed = true;
                                    finishCount++;
                                    MyFunc.AddMessage($"轴[{axis.AxisId}]回原点完成");
                                    return;
                                }
                                else
                                {
                                    GTSCard.AxisZeroSet(axis);
                                    GTSCard.ClearAlm1(axis);
                                    stepnum = 3;
                                }
                            }
                        }
                        else
                        {
                            GTSCard.AxisStop(axis, 0);
                            stepnum = 3;
                        }
                        break;
                    default:
                        break;
                }
                System.Threading.Thread.Sleep(100);
            }
        }

        public override string Description => "直线电机回原点模块：用于控制指定轴回归原点，支持多轴并行回零。";
    }
}
